<?php namespace module\material;

use module\WfSite;
use system\model\MaterialNews;

class Site extends WfSite
{
	//图片素材列表
	public function AdminImageLists()
	{
		$data = Db::table( 'material_images' )->paginate( 6 );
		View::with( 'data', $data );
		$this->display( 'image_lists' );
	}

	//讲图片素材推送到微信
	public function AdminPushImage()
	{
		$file=q('post.file');
		$res  = Wx::instance( 'Material' )->upload( 'image', $file );
		// echo json_encode($res);die;
		if ( is_array( $res ) && isset( $res['media_id'] ) ) {
			$data['path']     = $file;
			$data['media_id'] = $res['media_id'];
			$data['wx_path']  = $res['url'];
			Db::table( 'material_images' )->insert( $data );
			ajax( [ 'valid' => 1, 'message' => '上传成功', 'data' => $data ] );
		}
		ajax( [ 'valid' => 0, 'message' => '上传失败' ] );
	}

	//图文素材列表
	public function AdminNewsLists()
	{
		$data = Db::table('material_news')->paginate(6);
		View::with('data',$data);
		// p($data);die;
		$this->display('news_lists');
	}

	//添加图文素材
	public function AdminNewsPost()
	{
		if (IS_POST) {
			$res = Wx::instance('material')->addNews($_POST['data']);
			if (is_array($res) && isset($res['media_id'])) {
				$model = new MaterialNews();
				$model['content'] = Request::post('data');
				$model['media_id'] = $res['media_id'];
				$model->save();
				message( '保存成功', site_url( 'site/newsLists' ), 'success' );
			}
			message( '推送失败', '', 'error' );
		}
		$this->display('news_post');
	}

	//群发图文消息
	public function AdminSendall()
	{
		$id=Request::get('id');
		$media_id=Db::table('material_news')->where('id',$id)->pluck('media_id');
		$data=<<<str
{
   "filter":{
      "is_to_all":true
   },
   "mpnews":{
      "media_id":"$media_id"
   },
    "msgtype":"mpnews"
}
str;

		$res  = Wx::instance( 'message' )->sendall( $data );
	}

	//删除所有图片素材
	public function AdminDelall()
	{
		$type=Request::get('type');
		$data=[
			'type'=>$type,
			'offset'=>0,
			'count'=>20
		];
		$res=Wx::instance('material')->lists($data);
		// p($res);die;
		if ($type=='image') {
			$item=Db::table('material_images')->get();
			foreach ($item as $v) {
				Wx::instance('material')->delete($v['media_id']);
				unlink($v['path']);
				Db::table('material_images')->delete($v['id']);
			}

		}


		message('删除成功',site_url('site/imagelists'),'success');
	}

}